package cn.zc.web.video.api;



import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;


import org.springframework.stereotype.Component;

@Component
@ServerEndpoint(value = "/websocket/{name}")
public class WebSocketController {
    public static Integer userSum ;

    private Session session;

    private static ConcurrentHashMap<String, WebSocketController> webSockets = new ConcurrentHashMap<>();

    private static String user;

//    private static CopyOnWriteArraySet<WebSocketController> webSockets = new CopyOnWriteArraySet<WebSocketController>();


    /**
     * 创建连接，携带用户name
     * @param session
     * @param name
     * @throws IOException
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("name") String name) throws IOException {
        this.session = session;

        //判断连接中是否存在这个用户，若存在则先删除原有信息，再加入进来
        if(webSockets.containsKey(name)){
            webSockets.remove(name);
            webSockets.put(name,this);
        }else{
            webSockets.put(name, this);
        }
        userSum = webSockets.size();
        this.webSockets.get(name).session.getBasicRemote().sendText("链接成功");

    }

    /**
     * 连接错误
     * @param e
     */
    @OnError
    public void onError(Throwable e) throws IOException {
        webSockets.remove(user);
        session.close();
        //TODO 暂未做日志处理，先以打印处理
        System.out.println("用户：" + user + "发生错误——" + e.getMessage());
    }

    /**
     * 断开连接
     * @param name
     * @throws IOException
     */
    @OnClose
    public void onClose(@PathParam("name") String name) throws IOException {
        webSockets.remove(name);
        this.webSockets.get(name).session.getBasicRemote().sendText("用户" + name + "断开");
    }


    /**
     * 推送消息方法
     * @param data
     * @throws IOException
     */
    //TODO 不知道前端会传什么格式过来，以 ByteBuffer来接收
    @OnMessage
    public void onMessage(ByteBuffer data) throws IOException {
        Iterator<Map.Entry<String, WebSocketController>> iterator = webSockets.entrySet().iterator();
        //循环map中所有数据
        while (iterator.hasNext()) {
            Map.Entry entry = iterator.next();
            //admin作为播放者，不需要再次给他推流
            if (!entry.getKey().equals("admin")) {
                //其他用户直接进行流推送
                webSockets.get(entry.getKey()).session.getAsyncRemote().sendBinary(data);
            }

        }
    }
}
